package rainy.file.synchronization.client;

import java.io.File;
import java.io.FileInputStream;
import java.util.Base64;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import rainy.file.synchronization.client.file.FolderMonitor;
import rainy.file.synchronization.config.RainyRunTime;

/**
 * 
 * @author Grom
 *
 */
public class FileSendClient {

	private String host = RainyRunTime.getStringPropDefine("rainy.master.serverName", "localhost");
	private int port = RainyRunTime.getIntegerPropDefine("rainy.master.port", 9054);
	private String monitorFolder = RainyRunTime.getStringPropDefine("rainy.slaves.monitoring.folder", "/tmp");
	private static BlockingQueue<File> modifiedFilesQueue = new LinkedBlockingDeque<>();
	private static final Object key = new Object();

	public FileSendClient() {

	}

	public FileSendClient(String host, int port) {
		this.host = host;
		this.port = port;
	}

	public static void addNewAddedFile(File file) {
		synchronized (key) {
			modifiedFilesQueue.add(file);
		}
	}

	public void run() throws Exception {
		EventLoopGroup group = new NioEventLoopGroup();
		try {
			Bootstrap bootstrap = new Bootstrap().group(group).channel(NioSocketChannel.class)
					.handler(new SimpleChatClientInitializer());
			Channel channel = bootstrap.connect(host, port).sync().channel();
			System.out.println("[ client ] Client is started!");
			new FolderMonitor(monitorFolder).start();
			System.out.println("[ client ] Monitor is started!");
			boolean exit = false;
			while (true && !exit) {
				File newFile = null;
				synchronized (key) {
					System.out.println(modifiedFilesQueue);
					newFile = modifiedFilesQueue.poll();
					System.out.println(newFile);
				}
				if (newFile == null) {
					continue;
				}
				String sendStr = newFile.getPath().substring(monitorFolder.length()) + "#";
				// 发送该文件
				while (true) {
					if (newFile.getParentFile().exists() && newFile.exists() && newFile.canWrite()) {
						FileInputStream fins = new FileInputStream(newFile);
						byte[] buffer = new byte[fins.available()];
						fins.read(buffer);
						fins.close();
						sendStr += Base64.getEncoder().encodeToString(buffer);
						channel.writeAndFlush(sendStr + "\r\n");
						break;
					}
				}
			}
		} finally {
			group.shutdownGracefully();
		}
	}

	public static void main(String[] args) throws Exception {
		new FileSendClient().run();
	}
}